import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}, // 这里有一个空对象，为了放置后面取数据报错
    routes: constantRoutes
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      // 持久化存储
      setToken(newToken)
    },
    removeToken(state) {
      // 删除vuex的token
      state.token = null
      removeToken()
    },
    // 修改用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setRoutes(state, newRoutes) {
      state.routes = [...constantRoutes, ...newRoutes]
    }
  },
  actions: {
    async login(context, data) {
      const token = await login(data)
      context.commit('setToken', token)
    },
    // 获取用户信息的action
    async getUserInfo(context) {
      const result = await getUserInfo()
      context.commit('setUserInfo', result)
      return result
    },
    // 退出登录的action
    logout(context) {
      // 删除token
      context.commit('removeToken')
      // 设置用户信息为空对象
      context.commit('setUserInfo', {})
      // 重置路由
      resetRouter()
    }
  }
}
